package com.aa.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by RIOS on 2018/10/20.
 * Copyright © 2016年. 广州虫洞网络科技有限公司. All Rights Reserved .
 */
public class FileRead {
    public static final String[] novelType = new String[]{"text/plain"};
    public static final String[] picType = new String[]{"image/bmp", "image/jpeg", "image/png"};
    public static final String[] aviType = new String[]{"video/3gpp", "video/x-ms-asf", "video/x-msvideo",
            "video/vnd.mpegurl", "video/x-m4v", "video/quicktime", "video/mp4", "video/mpeg",
    };
    public static final String[] volumType = new String[]{"audio/x-mpegurl", "audio/mp4a-latm", "audio/x-mpeg", "audio/mpeg", "audio/ogg", "audio/x-wav", "audio/x-ms-wma"};
    public static final String[] docType = new String[]{"application/msword", "application/pdf", "application/vnd.ms-powerpoint", "text/plain", "application/vnd.ms-works"};
    public static final String[] zipType = new String[]{"application/x-gtar", "application/x-gzip", "application/x-compress", "application/zip"};

    public static void readNovelFlie(final Context context, final CallBack callBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    readFile(novelType, context, callBack);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private static void readFile(final String[] mimeType, Context context, final CallBack callBack) {
        LogUtils.d("readFile----------------");
        List<FileInfo> paths = new ArrayList<FileInfo>();
        Uri[] fileUri = null;
        fileUri = new Uri[]{MediaStore.Files.getContentUri("external")};

        String[] colums = new String[]{
                MediaStore.Files.FileColumns.DATA,
                MediaStore.Files.FileColumns.TITLE,
                MediaStore.Files.FileColumns.SIZE,
        };
        String[] extension = mimeType;

        //构造筛选语句
        String selection = "";
        for (int i = 0; i < extension.length; i++) {
            if (i != 0) {
                selection = selection + " OR ";
            }
            selection = selection + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE '%" + extension[i] + "'";
        }                     //获取内容解析器对象
        ContentResolver resolver = context.getContentResolver();
        //获取游标
        for (int i = 0; i < fileUri.length; i++) {
            Cursor cursor = resolver.query(fileUri[i], colums, null, null, null);
            LogUtils.d("readFile---cursor-------------");
            if (cursor == null) {
                callBack.result(null);
            }//游标从最后开始往前递减，以此实现时间递减顺序（最近访问的文件，优先显示）
            if (cursor.moveToLast()) {
                do {
                    //输出文件的完整路径
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.path = cursor.getString(0);
                    fileInfo.title = cursor.getString(1);
                    fileInfo.size = cursor.getString(2);
                    if (fileInfo.path != null && ( fileInfo.path.endsWith("txt"))) {
//                    if (fileInfo.path != null && (fileInfo.path.endsWith("umd") || fileInfo.path.endsWith("epub") || fileInfo.path.endsWith("txt"))) {
                        paths.add(fileInfo);
                    }
                } while (cursor.moveToPrevious());

            }
            cursor.close();
        }
        callBack.result(paths);
        LogUtils.d("readFile---end-------------");
    }

//    使用字符流的readline读取出来不能保留文档原格式，里面的空格换行都失效了。但是没有乱码。最终解决办法，是采用此方法，然后手动拼接换行符。
    public static String readTxtLine(String path) {
        StringBuffer txtContent = new StringBuffer();
        try {
            int len = 0;
            FileInputStream in = new FileInputStream(path);
            InputStreamReader reader = new InputStreamReader(in,codeString(path));
            BufferedReader br = new BufferedReader(reader);
            String str;
            while ((str = br.readLine()) != null) {
                if (len != 0) {// 处理换行符的问题，第一行不换行
                    txtContent.append(new String(("\n" + str).getBytes(), "utf-8"));
                } else {
                    txtContent.append(new String(str.getBytes(), "utf-8"));
                }
                len++;
            }
            reader.close();
            in.close();
        } catch (UnsupportedEncodingException | FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        LogUtils.d(txtContent.toString());
        return txtContent.toString();
    }

    /**
     * 判断文件的编码格式
     * @param fileName :file
     * @return 文件编码格式
     * @throws Exception
     */
    private static String codeString(String fileName) throws Exception{
        BufferedInputStream bin = new BufferedInputStream(
                new FileInputStream(fileName));
        int p = (bin.read() << 8) + bin.read();
        String code = null;

        switch (p) {
            case 0xefbb:
                code = "UTF-8";
                break;
            case 0xfffe:
                code = "Unicode";
                break;
            case 0xfeff:
                code = "UTF-16BE";
                break;
            default:
                code = "GBK";
        }

        return code;
    }


    public interface CallBack {
        void result(List<FileInfo> localPath);
    }


}
